<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\MedicalRecord;
use App\Models\Patient;
use App\Project\Scene\MedicalScene;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Builder as QueryBuilder;
use App\LogicService\Contracts\HospitalManageLogicContract;

class IndexController extends Controller
{
    /**
     * @var \App\Project\Scene\MedicalScene
     */
    protected $scene;

    /**
     * @var \App\Models\Patient
     */
    protected $patient;

    protected $table;

    protected $where;

    protected $hospitalManage;

    protected $hospital_ids;

    /**
     * IndexController constructor.
     * @param \App\Project\Scene\MedicalScene $scene
     * @param \App\Models\Patient $patient
     *
     */
    public function __construct(MedicalScene $scene, Patient $patient, HospitalManageLogicContract $hospitalManage)
    {
        $this->scene = $scene;
        $this->patient = $patient;
        $this->hospitalManage = $hospitalManage;
        $this->table = $this->patient->getTable();
    }

    public function index()
    {
        if ($this->scene->getUser()->isDoctor()) {
            $this->where[] = ['st_medical_records.hospital_id', '=', $this->scene->getHospital()->id];
            $this->where[] = ['st_medical_records.doctor_id', '=', $this->scene->getUser()->id];
        } elseif ($this->scene->getUser()->isDoctorsAdmin()) {
            $this->where[] = ['st_medical_records.hospital_id', '=', $this->scene->getHospital()->id];
        } elseif ($this->scene->getUser()->isRegionAdmin()) {

            $hospitalManage = $this->hospitalManage->show($this->scene->getUser()->account);
            $this->hospital_ids = json_decode($hospitalManage->hospital_ids);
            $this->hospital_ids[] = $this->scene->getHospital()->id;
        }

        $this->where[] = ['st_medical_records.doctor_id', '>', 0];

        $results = [];
        $results[0]['type'] = '';
        $results[0]['name'] = '全部病历';
        $results[0]['patient_count'] = $this->patientBuilder()->count('tn_user_base.id');
        $results[0]['record_count'] = $this->builder();

        if (!$this->scene->isWestern()) {
            foreach (Patient::$diabetes_stage_type_keys as $key => $value) {
                $results[$key]['type'] = $key;
                $results[$key]['name'] = Patient::$diabetes_stage_types [$key];
                $results[$key]['patient_count'] = $this->patientBuilder()->diabetesStage($key)->count('tn_user_base.id');
                $results[$key]['record_count'] = $this->builder($key);
            }
        }

        $user = \Auth::user();
        $user->LASTLOGIN = date('Y-m-d H:i:s',time());
        $user->save();

        return view('dashboard.index')->with('results', $results);
    }

    protected function builder($stage = null)
    {
        if ($this->scene->getUser()->isRegionAdmin()) {

            return MedicalRecord::whereIn('patient_id', function (QueryBuilder $query) use ($stage) {
                $query->from('tn_user_base')
                    ->select('tn_user_base.id')
                    ->join('st_medical_records', 'tn_user_base.id', 'st_medical_records.patient_id')
                    ->where('tn_user_base.type', 1)
                    ->whereIn('st_medical_records.hospital_id',$this->hospital_ids)
                    ->distinct();
                if ($stage) {
                    $query->where('diabetes_stage', $stage);
                }
            })->where('hospital_id','>',0)->count();

        }
        return MedicalRecord::whereIn('patient_id', function (QueryBuilder $query) use ($stage) {
            $query->from('tn_user_base')
                ->select('tn_user_base.id')
                ->join('st_medical_records', 'tn_user_base.id', 'st_medical_records.patient_id')
                ->where('tn_user_base.type', 1)->where($this->where)->distinct();
            if ($stage) {
                $query->where('diabetes_stage', $stage);
            }
        })->where('hospital_id','>',0)->count();
    }

    /**
     * @return Builder
     */
    public function patientBuilder()
    {

        if ($this->scene->getUser()->isRegionAdmin()) {

            return $this->patient
                ->join('st_medical_records', 'tn_user_base.id', 'st_medical_records.patient_id')
                ->whereIn('st_medical_records.hospital_id',$this->hospital_ids)
                ->distinct();
        }
        return $this->patient
            ->join('st_medical_records', 'tn_user_base.id', 'st_medical_records.patient_id')
            ->where($this->where)
            ->distinct();
    }
}
